/* **************************************************************************/
/*COPYRIGHT CCWIN-IN ALL RIGHTS RESERVED. THIS IS AN UNPUBLISHED WORK.      */
/*V8:ConvertMode=Report                                                     */
/*V8:WebEnabled=Yes                                                         */
/*V8:RunMode=Character,Windows                                              */
/*EXTRACTING DATA FROM MFG/PRO                                              */
/****************************************************************************/
/* PROCEDURE NAME        : xxcstctrexptapi.p                                */
/* PROCEDURE TYPE        : API export Process                               */
/* DESCRIPTION           : CostCenter export Process                        */
/*                                                                          */     
/* INCLUDE FILES         :                                                  */
/* CALLED BY             :                                                  */
/* CALLED PROCEDURES     :                                                  */
/****************************************************************************/
/* CREATED BY            : Gaoyan                                 5-Mar-24  */
/****************************************************************************/ 
/****************************************************************************/
/****************************************************************************/

{us/mf/mfdtitle.i}
{us/bbi/gplabel.i}
{us/wb/wbrp01.i}

{xxjson.i}
{xxcimload.i}


define input parameter vc_inputjson             as character format "x(60)" no-undo.
define input parameter vc_outputjson            as character format "x(60)" no-undo.
define input parameter vc_import                as logical  no-undo.

define variable l_error                      as character      no-undo.
define stream f_log.
define stream f_cim.
define variable v_quote               as character initial """"   no-undo.
define variable v_default             as character initial "-"    no-undo.
define variable v_space               as character initial " "    no-undo.
define variable v_log                 as character                no-undo.
define variable v_cim                 as character                no-undo.
define variable v_fline               as character                no-undo.
define variable v_errorstatus         as logical                  no-undo.
define variable v_toterrorstatus      as logical initial yes      no-undo.
define variable v_errstring           as character                no-undo.
define variable v_status              as character                no-undo.

define variable v_entity              like si_entity              no-undo.
define variable v_ee                  as logic                    no-undo.

define variable vi_filecount          as integer                  no-undo.
define variable vc_filename           as character                no-undo.
define variable vc_topath             as character                no-undo.
define variable v_runproagram        as character                no-undo.
define variable vc_traceid            as character                no-undo.

/*=============================================================================*/
/********************* Input Criteria variable definitions**********************/
/*=============================================================================*/

define new shared variable ip_entity1      as character no-undo.
define new shared variable ip_entity2      as character no-undo.
define new shared variable ip_custsupp1    as character no-undo.
define new shared variable ip_custsupp2    as character no-undo.
define new shared variable ip_glacct1      as character no-undo.
define new shared variable ip_glacct2      as character no-undo.
define new shared variable ip_daybook1     as character no-undo.
define new shared variable ip_daybook2     as character no-undo.
define new shared variable ip_curr1        as character no-undo.
define new shared variable ip_curr2        as character no-undo.
define new shared variable ip_agingtyp     as character no-undo.
define new shared variable ip_seltype      as character no-undo.
define new shared variable ip_agcaltyp     as character no-undo.
define new shared variable ip_asofdt       as date      no-undo.   
define new shared variable ip_agcaldt      as date      no-undo.
define new shared variable ip_effdate1     as date      no-undo.
define new shared variable ip_effdate2     as date      no-undo.

   

/* TEMP-TABLE DEFINITION BLOCK */

define temp-table ttsinvbalance no-undo
   field tt_supplier             like Creditor.CreditorCode
   field tt_custorsupp               as   char
   field tt_company               like Company.CompanyCode
   field tt_supplier_type             like CreditorType.CreditorTypeCode
   field tt_name1         like BusinessRelation.BusinessRelationName1
   field tt_name2         like BusinessRelation.BusinessRelationName2
   field tt_name3         like BusinessRelation.BusinessRelationName3
   field tt_glcode          like GL.GLCode
   field tt_year            like CInvoice.CInvoicePostingYear
   field tt_voucher          as character
   field tt_reference              like CInvoice.CInvoiceReference
   field tt_Invoiceno        as   character 
   field tt_curr             like Currency.CurrencyCode
   field tt_due_date            like CInvoice.CInvoiceDueDate
   field tt_eff_date            like CInvoice.CInvoicePostingDate
   field tt_inv_date            like CInvoice.CInvoiceDate
   field tt_credit_term              like PaymentCondition.PaymentConditionCode
   field tt_tc_amt           like CInvoice.CInvoiceOriginalDebitTC
   field tt_bc_amt           like CInvoice.CInvoiceOriginalDebitLC
   field tt_tcbal            like CInvoice.CInvoiceOriginalDebitTC
   field tt_bcbal            like CInvoice.CInvoiceOriginalDebitTC
   field tt_bcurr            like Currency.CurrencyCode

.


   
define temp-table ttSearchCondition no-undo

    field entity_from             as character
    field entity_to               as character
    field supplier_from           as character
    field supplier_to             as character
    field glacct_from             as character
    field glacct_to               as character
    field curr                    as character
    field yearperiod_from         as integer
    field yearperiod_to           as integer
    field AS_OF_DATE              as date
    field select_type             as character
    
      .  


define variable inv_age     as integer                     no-undo.
define variable age_date    as date                        no-undo.
define variable tmp-msg     as char format "x(20)"         no-undo.
define variable v_paidamttc like CDocumentOriginalCreditTC no-undo.
define variable v_paidamtlc like CDocumentOriginalCreditLC no-undo.
define variable m_adjamttc  as Decimal no-undo. 
define variable m_adjamtlc  as Decimal no-undo.  

      
DEFINE DATASET dsSearchCondition FOR ttSearchCondition.

hdataset = dataset dsSearchCondition:HANDLE.   
        
DEFINE DATASET dssinvbalance FOR ttsinvbalance.

hresult = dataset dssinvbalance:HANDLE.    
             

mainloop:
   repeat on error undo mainloop, leave mainloop:
     
    
      /* Output and Batch Input */
      
      {us/xx/xxworkpath_e.i &outbound=YES &inbound=no &archive=YES}
   
   assign m_outpath     = m_outpath + "sinv/"
          m_archpath    = m_archpath + "sinv/"
          m_successpath = m_successpath + "sinv/"
          m_errorpath   = m_errorpath + "sinv/"
          m_workpath    = m_workpath + "sinv/".
   
   
      empty temp-table ttsinvbalance         no-error.
      
      
      /* Load SEARCH conditions from JSON  */ 
      
      vc_outputjson = replace(vc_inputjson,".json",".run.out.json").   
      run loadjsonfile(input vc_inputjson,
                       input vc_outputjson,
                       output vl_RetOK).
                       
   if vl_RetOK then do:
   
   if ip_entity2   = hi_char then ip_entity2   = "".       
   if ip_custsupp2 = hi_char then ip_custsupp2 = "".
   if ip_glacct2   = hi_char then ip_glacct2   = "".
   if ip_curr2     = hi_char then ip_curr2     = "".
  


   for each ttSearchCondition.

       assign ip_entity1 = ttSearchCondition.entity_from
              ip_entity2 = ttSearchCondition.entity_to 
              ip_custsupp1 = ttSearchCondition.supplier_from 
              ip_custsupp2 = ttSearchCondition.supplier_to
              ip_glacct1   = ttSearchCondition.glacct_from 
              ip_glacct2   = ttSearchCondition.glacct_to 
              ip_asofdt    = ttSearchCondition.AS_OF_DATE
              ip_seltype   = ttSearchCondition.select_type
              ip_agcaldt   = ttSearchCondition.AS_OF_DATE
              ip_curr1     = ttSearchCondition.curr
              ip_curr2     = ttSearchCondition.curr.
   end. /* for each ttSearchCondition. */
   
   if ip_entity2   = "" then ip_entity2   = hi_char.
   if ip_custsupp2 = "" then ip_custsupp2 = hi_char.
   if ip_glacct2   = "" then ip_glacct2   = hi_char.
   if ip_curr2     = "" then ip_curr2     = hi_char.

   if ip_asofdt    = ?  then ip_asofdt    = today.
   if ip_effdate1   = ?  then ip_effdate1   = today.
   if ip_effdate2   = ?  then ip_effdate2  = today.




   /*OUTPUT data preparation*/
 
      for each Company  
         where Company.CompanyCode >= ip_entity1
         and Company.CompanyCode <= ip_entity2
      no-lock,
      each CInvoice of Company
      no-lock,
      first Currency 
         where Currency.Currency_ID = CInvoice.CInvoiceCurrency_ID
         and Currency.CurrencyCode >= ip_curr1
         and Currency.CurrencyCode <= ip_curr2
      no-lock,
      first Journal of CInvoice  no-lock,
      first GL  
         where GL.GL_ID = CInvoice.ControlGL_ID
         and GL.GLCode >= ip_glacct1
         and GL.GLCode <= ip_glacct2
      no-lock,
      first Creditor of CInvoice  
         where Creditor.CreditorCode >= ip_custsupp1
         and Creditor.CreditorCode <= ip_custsupp2
      no-lock,
      first BusinessRelation of Creditor  no-lock,
      first PaymentCondition  
         where PaymentCondition.PaymentCondition_ID = CInvoice.NormalPaymentCondition_ID 

      no-lock:

         if ip_seltype  = "INV" 
            and Cinvoice.CInvoiceDate > ip_asofdt
         then
            next.
         else if ip_seltype  = "EFF" 
            and Cinvoice.CInvoicePostingDate > ip_asofdt
         then
            next.
         else if ip_seltype  = "DUE" 
            and Cinvoice.CInvoiceDueDate > ip_asofdt
         then
            next. 

      
            find first CreditorType of Creditor no-lock no-error.

         assign            
          v_paidamttc = 0
          v_paidamtlc = 0
                   .

         Assign
           m_adjamttc   = 0
           m_adjamtlc   = 0. 

         For each OIAdjustLn where OIAdjustLn.CInvoice_ID = cinvoice.CInvoice_ID
         no-lock :
           Assign
              m_adjamttc  = m_adjamttc + OIAdjustLnMovementAmtTC
              m_adjamtlc  = m_adjamtlc + OIAdjustLnMovementAmtLC .
         End.


         for each cDocumentinvoicexref of cinvoice
         no-lock,
         first cdocument of cDocumentinvoicexref
         no-lock,
         first CDocumentPostingline of cdocument
         no-lock,
         first Postingline of CDocumentPostingline
            where PostingDate <= ip_agcaldt
         no-lock:
                   
            assign
             v_paidamttc = v_paidamttc + CDocumentOriginalDebitTC - CDocumentOriginalCreditTC - m_adjamttc       
             v_paidamtlc = v_paidamtlc + CDocumentOriginalDebitLC - CDocumentOriginalCreditLC - m_adjamtlc       
             .
         end.       


         if CInvoice.CInvoiceOriginalDebitTC - Cinvoice.CInvoiceOriginalCreditTC - v_paidamttc = 0
         then
            next.
        

        create ttsinvbalance.
            assign    
            tt_custorsupp       = "Suppliers"
            tt_supplier     = Creditor.CreditorCode                                
            tt_company       = Company.CompanyCode .

            if available CreditorType
            then
               tt_supplier_type     = CreditorType.CreditorTypeCode .
            else 
               tt_supplier_type     = "".

            assign
               tt_name1 = BusinessRelation.BusinessRelationName1
               tt_name2 = BusinessRelation.BusinessRelationName2
               tt_name3 = BusinessRelation.BusinessRelationName3 
               tt_glcode  = GL.GLCode                                                                                                           
               tt_year    = CInvoice.CInvoicePostingYear                                          
               tt_voucher  = string( CInvoice.CinvoiceVoucher,"999999999")                                              
               tt_reference      = CInvoice.CInvoiceReference   
               tt_Invoiceno = string( CInvoice.CinvoicepostingYear) + "/" +
               Journalcode + string( CInvoice.CinvoiceVoucher,"999999999")
               tt_curr     = Currency.CurrencyCode
               tt_bcurr    = base_curr
               tt_due_date    = CInvoice.CInvoiceDueDate                                              
               tt_eff_date    = CInvoice.CInvoicePostingDate                                          
               tt_inv_date    = CInvoice.CInvoiceDate                                                 
               tt_credit_term      = PaymentCondition.PaymentConditionCode                                   
               tt_tc_amt   = CInvoice.CInvoiceOriginalDebitTC - Cinvoice.CInvoiceOriginalCreditTC    
               tt_bc_amt   = CInvoice.CInvoiceOriginalDebitLC - Cinvoice.CInvoiceOriginalCreditLC 
               tt_tcbal    = 0   
               tt_bcbal    = 0   
               .


         
                  
         age_date = ?.
         if ip_agcaltyp = "INV" then
            age_date =  Cinvoice.CInvoiceDate.
         else if ip_agcaltyp = "EFF" then
            age_date =  Cinvoice.CInvoicePostingDate.
         else if ip_agcaltyp = "DUE" then
            age_date =  Cinvoice.CInvoiceDueDate.
         
                
      
         for each CInvoiceMovement of CInvoice
         no-lock,
         each PostingLine of CInvoiceMovement
         no-lock:   

            if CInvoiceMovementType      = "MOVEMENT"   
               and CInvoiceMovementPostDate  > ip_agcaldt
            then
               next.

            assign   
               tt_tcbal = tt_tcbal + (PostingLine.PostingLineDebitTC - PostingLine.PostingLineCreditTC)
               tt_bcbal = tt_bcbal + (PostingLine.PostingLineDebitLC - PostingLine.PostingLineCreditLC).

           
            end. /* for each CInvoiceMovement */     

            if tt_bcbal = 0 
            then 
               delete ttsinvbalance.   

       END.  /*    for each Company   */


       end.  /* if vl_RetOK then do: */ 
                    
       /* Create output json */                   
       run writejsonfile(input hresult,
                input vc_outputjson,
                input "FILE",
                input True,
                input "UTF-8",
                output vl_RetOK,
                output vc_errorstring).
                
     do vi_filecount = 1 to 5:
        /* when success move cim log file to archive directory  */
        /* when failed move cim log file to error directory  */   
        /*  move status json file to out directory for API return */   
        /* when success move previous step .p and json file to archive directory  */
        /* when failed move previous step .p and json file to error directory  */       
        case vi_filecount:
    
        when 1 then
        assign vc_filename = replace(vc_inputjson,".json",".p")
               vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
        when 2 then
        assign vc_filename = vc_inputjson
               vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
        when 3 then
        assign vc_filename = replace(vc_inputjson,".json",".dat")
               vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
        when 4 then
        assign vc_filename = replace(vc_inputjson,".json",".run.log")
               vc_topath   = m_outpath.
        when 5 then
        assign vc_filename = replace(vc_inputjson,".json",".run.out.json")
               vc_topath   =  m_outpath.
        end case.
        
       if vl_RetOK then 
       put unformatted vc_filename " " skip
       vc_topath " " skip 
       vi_filecount skip.
   
      
        
        run cimfilehandle(input vc_filename,
                          input vc_topath,
                          input no ).                 
                 
        
   
     end.       /* do vi_filecount = 1 to 5: */        
    
 
 
 leave.
end. /* repeat on error undo mainloop, leave mainloop: */
